package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.RoleDao;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;


@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionDao permissionDao;


    @Override
    public User findByUsername(String username) {

        User user = userDao.findByUsername(username);

        if (user == null)
            return null;

        Integer userId = user.getId();

        //通过userId查询用户具有那些角色
        Set<Role> roles = roleDao.findRoleByUserId(userId);

        //遍历角色 查询出每个角色包含的权限
        for (Role role : roles) {

            //角色id
            Integer roleId = role.getId();
            //权限集合
            Set<Permission> permissions = permissionDao.findPermissionByRoleId(roleId);

            //给角色设置权限
            role.setPermissions(permissions);
        }

        //给用户设置角色
        user.setRoles(roles);
        return user;
    }
}
